package com.ccc3gc.servlet;

import com.ccc3gc.dao.UserDao;
import com.ccc3gc.dao.impl.UserDaoImpl;
import com.ccc3gc.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserDao userDao = new UserDaoImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String autoLogin = req.getParameter("autoLogin");
        User user = userDao.selectUserByUserName(username);
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        if (user != null && user.getPassword().equals(password)) {
            req.getSession().setAttribute("user", user);
            if (autoLogin != null) {
                Cookie cookie = new Cookie("username", username);
                cookie.setMaxAge(30 * 60);
                resp.addCookie(cookie);
            }
            writer.println("<script>alert('成功');location.href='success.jsp'</script>");
//            resp.sendRedirect("success.html");
        } else {
            writer.println("<script>alert('登录失败');location.href='login.html'</script>");
//            resp.sendRedirect("login.html");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
